package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.NavDao;
import com.cn.wanxi.dao.impl.NavImpl;
import com.cn.wanxi.model.NavModel;
import com.cn.wanxi.service.NavService;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

public class NavServiceImpl implements NavService {
    private NavDao navDao = new NavImpl();

    @Override
    public List<NavModel> getNavModelList() {
//        判断是否存在
        Jedis jedis = new Jedis();
        jedis.select(10);
        List<NavModel> list = new ArrayList<>();
        boolean isHave = jedis.exists("hrefs");
        if (isHave) {
//            取redis
            List<String> hrefs = jedis.lrange("hrefs", 0, jedis.llen("hrefs"));
            List<String> titles = jedis.lrange("titles", 0, -1);
            for (int i = 0; i < hrefs.size(); i++) {
                NavModel model = new NavModel();
                model.setHref(hrefs.get(i));
                model.setTitle(titles.get(i));
                list.add(model);
            }
            System.out.println("resdis");
        } else {
//            取数据库
            list = navDao.getNavModelList();
//            存redis
//            如果你们想存对象，可以自己封装
            for (int i = 0; i < list.size(); i++) {
                jedis.rpush("hrefs", list.get(i).getHref());
                jedis.rpush("titles", list.get(i).getTitle());
//                jedis.set("book:"+list.get(i).getId(),"a");

            }
            System.out.println("mysql");

        }
        return list;
    }
}
